import {Blog} from "../model/Blog.js"
import { Op } from "sequelize";
const fn_list =async(ctx,next)=>{
    let keyword = ctx.request.query.keyword || ''
    console.log(keyword);
    
    let where
    if (keyword) {
        where = {
            [Op.or]: [
                {
                    title: {
                        [Op.like]: `%${keyword}%`
                    },

                },
                {
                    author: {
                        [Op.like]: `%${keyword}%`
                    },

                },

            ]
        }
    }
    let blogs = await Blog.findAll(
        { where }
    );
    ctx.body = {
        code: 1000,
        msg: '列表成功',
        data: blogs
    }
}

const fn_getById =async(ctx,next)=>{
    let id = ctx.params.id || 0;
    let blog = await Blog.findByPk(id);
    ctx.body = {
        code: 1000,
        msg: '成功',
        data: blog
    }
}
const fn_add =async(ctx,next)=>{
    let obj = ctx.request.body;

    // obj存在，并且obj有title、author属性，并且title长度在1~80 ，author长度在6~30
    if (obj && obj.title && obj.author && obj.title.length > 0 && obj.title.length < 80 && obj.author.length > 5 && obj.author.length <= 30) {
        let blog = await Blog.create(obj);
        ctx.body = {
            code: 1000,
            msg: '新增成功',
            data: blog
        }
    } else {
        ctx.body = {
            code: 3000,
            msg: '标题或者作者验证不通过，请修改后重试'
        }
    }
    
}
const fn_edit =async(ctx,next)=>{
     let id = ctx.params.id || 0;
    let obj = ctx.request.body;
    await Blog.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: '修改成功',
        data: null
    }
}
const fn_del =async(ctx,next)=>{
    ctx.body='删除'
    let id =ctx.params.id ||0
    let count=await Blog.destroy({
        where:{id:id}
    })
    let res;
    if (count===1){
        res={
            code:1000,
            msg:'删除成功',
            data:null
        }
    }
    else{
        res={
            code:4000,
            msg:'删除失败',
            data:null
        }
    }
    ctx.body=res;
};

export default[
    {
        method:'get',
        url:'/blogs',
        fn:fn_list
    },
    {
        method:'get',
        url:'/blogs/:id',
        fn:fn_getById
    },
    {
        method:'post',
        url:'/blogs',
        fn:fn_add
    },
    {
        method:'put',
        url:'/blogs/:id',
        fn:fn_edit
    },
    {
        method:'del',
        url:'/blogs/:id',
        fn:fn_del
    }
]